﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MotoCommon;
using System.IO;

namespace Demo02
{
    public partial class FrmScan : Form
    {
        private string _sScanResultFile = @"\Application Data\ScanData.txt";	// 数据文件
        private string _sBarText = "";					// 临时保存提示信息
        private bool _bIsRewrite = false;				// 记录编辑状态
        private EventHandler _eventHandler = null;		// 保存Reader在本窗体的委托
        private List<MyGoods> _scanList = null;
        public FrmScan()
        {
            InitializeComponent();
        }

        #region
        private void txtBAmount_KeyUp(object sender, KeyEventArgs e)
        {
            HandlerKeyUp(e);
        }

        private void FrmScan_Closed(object sender, EventArgs e)
        {
            
        }

        private void FrmScan_Load(object sender, EventArgs e)
        {
            if (!File.Exists(_sScanResultFile))
            {
                File.Create(_sScanResultFile);
            }
            MotoReaderAction.InitReader();
            LoadData();
            // 居中窗体
            this.Height = 212;
            this.Location = MyUtility.CenterWindow(this);
            _eventHandler = new EventHandler(MyReader_ReadNotify);
            MotoReaderAction.reader.ReadNotify += _eventHandler;
            MotoReaderAction.StartRead();	// 开始Reader读取
            // 开始扫描引擎的读取
           
            sBar.Text = "等待扫描...";

            ResetForm();	// 重置界面
        }

        private void FrmScan_GotFocus(object sender, EventArgs e)
        {
            
        }

        private void FrmScan_KeyUp(object sender, KeyEventArgs e)
        {
            HandlerKeyUp(e);
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            sBar.Text = _sBarText;
            timer1.Enabled = false;
        }
        #endregion

        #region 私有函数
        /// <summary>
        /// 重置界面
        /// </summary>
        private void ResetForm()
        {
            this.lbBarcode.Text = "";
            this.txtBAmount.Text = "";
            this.lbName.Text = "";
            this.lbDate.Text = "";
            this.txtBAmount.Focus();
        }

        private void HandlerKeyUp(KeyEventArgs e)
        {
            // 如果是"120"或"17"键,退出判断,因为发现每次加载窗体都反复数次这两个键.
            if (e.KeyValue == (char)120)
                this.Close();

            // 如果用户敲击"Esc"键,退出系统.
            if (e.KeyValue == (char)27)
            {
                // 关闭扫描的读取
                MotoReaderAction.reader.ReadNotify -= _eventHandler;
                MotoReaderAction.StopRead();

                // CE的CF不能正确回收Enabled=true的Timer资源,所以关闭窗体之前要显示地关闭Timer.郁闷!!!
                timer1.Enabled = false;
                timer1.Dispose();

                this.Close();
                return;
            }

            // 如果条码没有被扫描,则退出其他键盘响应
            if (lbBarcode.Text == "")
                return;

            if (e.KeyValue == (char)13)	// 如果用户按回车键
            {
                if (MyUtility.IsInt(txtBAmount.Text))	// 如果输入的物品数量是正确的Int类型
                {
                    

                    // 提交数据
                    if (!_bIsRewrite)	// 追加数据
                    {
                        MyGoods record = new MyGoods();
                        record.BarCode = lbBarcode.Text;
                        record.GoodsName = lbName.Text;
                        record.GoodsAmount = Convert.ToInt32(txtBAmount.Text);
                        record.GoodsDate = lbDate.Text;
                        _scanList.Add(record);

                        string sData = string.Format("{0},{1},{2},{3}",lbBarcode.Text,lbName.Text,txtBAmount.Text,lbDate.Text);
                        if (AppendToFile(sData))
                            ResetForm();	// 重置界面
                    }
                    else	// 改写状态
                    {
                        foreach (MyGoods record in _scanList)
                        {
                            if (record.BarCode.Trim() == lbBarcode.Text.Trim())
                            {
                                record.GoodsAmount = Convert.ToInt32(txtBAmount.Text);
                                break;
                            }
                        }
                        if (UpdateToFile(lbBarcode.Text, txtBAmount.Text))	// 执行改写操作
                            ResetForm();	// 重置界面
                    }
                }
                else
                {
                    ShowTip("数量不正确!");
                }
            }
            else if (e.KeyValue == (char)113 && _bIsRewrite)	// 如果是"改写状态"并且按"F"+"F2"键
            {
                if (DelToFile(lbBarcode.Text))	// 执行删除记录操作
                    ResetForm();	// 重置界面
            }
            else if (e.KeyValue == (char)121)	// 按"F"+"F2"键
            {
                //显示数据列表
                MotoCommon.MotoReaderAction.turnOnBacklight();
            }
            else if (e.KeyValue == (char)114)	// 按"F"+"F2"键
            {
                //显示数据列表
                MotoCommon.MotoReaderAction.turnOffBacklight();
            }

        }

        /// <summary>
        /// Reader的ReadNotify事件处理程序
        /// </summary>
        private void MyReader_ReadNotify(object sender, EventArgs e)
        {
            // 如果读取成功
            if (MotoReaderAction.readerData.Result == Symbol.Results.SUCCESS)
            {
                MotoReaderAction.StartRead();	// 再次开始Reader读取
                sBar.Text = "等待扫描...";

                string sText = MotoReaderAction.readerData.Text;	// 从这个reader中提取数据,并显示在界面上
                lbBarcode.Text = sText;
                //判断该货物是否在货物列表中
                bool bTempHasGoods = false;
                foreach (MyGoods record in FrmMain.GoodsList)
                {
                    if (sText == record.BarCode)
                    {
                        bTempHasGoods = true;
                        lbName.Text = record.GoodsName;
                        lbDate.Text = record.GoodsDate;
                        txtBAmount.Text = record.GoodsAmount.ToString();
                    }
                }

                if (!bTempHasGoods)
                {
                    //if (MessageBox.Show("列表中不存在该货物，是否继续？", "提示",
                    //    MessageBoxButtons.OKCancel, MessageBoxIcon.Question,
                    //    MessageBoxDefaultButton.Button1) != DialogResult.OK)
                    //{
                    //    ResetForm();
                    //}
                    //else
                    //{
                       
                    //}
                    lbName.Text = "无名称";
                    lbDate.Text = string.Format("{0:yyyyMMdd}", DateTime.Now);
                }
                
                txtBAmount.Text = "";
                
                int iAmount = IsReScan(sText);
                if (iAmount == -1)
                {
                    //将填写的数量读入
                    _bIsRewrite = false;
                }
                else
                {
                    txtBAmount.Text = iAmount.ToString();
                    _bIsRewrite = true;
                }
                //
                txtBAmount.Focus();	// 设置输入焦点到"物品数量"编辑框
                
                // 匹配是否为改写记录

            }
        }

        /// <summary>
        /// 在状态栏中显示提示
        /// </summary>
        /// <param name="tip">提示内容</param>
        private void ShowTip(string tip)
        {
            _sBarText = sBar.Text;
            sBar.Text = tip;
            timer1.Enabled = true;
        }

        /// <summary>
        /// 匹配已经存储的数据中是否有相同的信息.如果有返回物品数量,如果没有返回-1.
        /// </summary>
        /// <param name="sBarcodeData">条码数值</param>
        /// <returns>物品数量</returns>
        private int GetAmount(string sBarcodeData)
        {
            StreamReader sr = new StreamReader(_sScanResultFile, System.Text.Encoding.Default);
            try
            {
                String sLine;
                while ((sLine = sr.ReadLine()) != null)
                {
                    string[] sData = sLine.Split(new Char[] { });
                    if (sData[0] == sBarcodeData)
                    {
                        return int.Parse(sData[1]);
                    }
                }
                return -1;
            }
            catch
            {
                ShowTip("匹配数据异常!");
                return -1;
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }
        }

        /// <summary>
        /// 向数据文件追加记录.
        /// </summary>
        /// <param name="sValue">要追加的记录.</param>
        /// <returns>成功返回True,否则返回False.</returns>
        private bool AppendToFile(string sValue)
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(_sScanResultFile, true, System.Text.Encoding.Default))
                {
                    sw.WriteLine(sValue);
                    ShowTip("创建记录成功.");
                }                
                return true;
            }
            catch
            {
                ShowTip("创建记录失败!");
                return false;
            }
        }

        /// <summary>
        /// 向数据文件更改记录.
        /// </summary>
        /// <param name="sPN">要更改记录的P/N.</param>
        /// <param name="sNum">要更改记录的Num.</param>
        /// <returns>成功返回True,否则返回False.</returns>
        private bool UpdateToFile(string sPN, string sNum)
        {
            // 整理数据
            List<string> sResult = new List<string>();
            try
            {

                using (StreamWriter sw = new StreamWriter(_sScanResultFile, false, System.Text.Encoding.Default))
                {
                    foreach (MyGoods record  in _scanList)
                    {
                        sw.WriteLine(string.Format("{0},{1},{2},{3}", record.BarCode, record.GoodsName, record.GoodsAmount, record.GoodsDate));
                    }
                }
                return true;
            }
            catch
            {
                ShowTip("整理修改记录失败!");
                return false;
            }

     
        }

        /// <summary>
        /// 向数据文件删除记录.
        /// </summary>
        /// <param name="sPN">要删除记录的P/N.</param>
        /// <returns>成功返回True,否则返回False.</returns>
        private bool DelToFile(string sPN)
        {
            // 整理数据
            List<string> sResult = new List<string>();
            try
            {
                using (StreamReader sr = new StreamReader(_sScanResultFile, System.Text.Encoding.Default))
                {
                    String sLine;
                    while ((sLine = sr.ReadLine()) != null)
                    {
                        List<string> sList = MotoCommon.MotoCommon.splitStr(sLine, ',');
                        if (sList[0] != sPN)
                        {
                            sResult.Add(sLine);
                        }
                    }
                }

                using (StreamWriter sw = new StreamWriter(_sScanResultFile, true, System.Text.Encoding.Default))
                {
                    foreach (string str in sResult)
                    {
                        sw.WriteLine(str);
                    }
                }
                return true;
            }
            catch
            {
                ShowTip("整理修改记录失败!");
                return false;
            }
        }

        private int IsReScan(string code)
        {
            if (!File.Exists(_sScanResultFile))
            {
                return -1;
            }
           
            try
            {
                int ret = -1;
                foreach (MyGoods record in _scanList)
                {
                    if (code.Trim() == record.BarCode.Trim())
                    {
                        ret = record.GoodsAmount;
                        break;
                    }
                }
                return ret;
                //using (StreamReader sr = new StreamReader(_sScanResultFile, System.Text.Encoding.Default))
                //{
                //    String sLine;
                //    while ((sLine = sr.ReadLine()) != null)
                //    {
                //        List<string> sList = MotoCommon.MotoCommon.splitStr(sLine, ',');
                //        if (sList[0].Trim() == code.Trim())
                //            return Convert.ToInt32(sList[1]);

                //    }
                //    return -1;
                //}
            }
            catch
            {
                ShowTip("匹配数据异常!");
                return -1;
            }
        }

        private void LoadData()
        {
            _scanList = new List<MyGoods>();
            if (!File.Exists(_sScanResultFile))
            {
                
                return;
            }
            using (StreamReader sr = new StreamReader(_sScanResultFile, System.Text.Encoding.Default))
            {
                String sLine;
                while ((sLine = sr.ReadLine()) != null)
                {
                    List<string> sList = MotoCommon.MotoCommon.splitStr(sLine, ',');
                    if (sList.Count == 4)
                    {
                        try
                        {
                            MyGoods record = new MyGoods();
                            record.BarCode = sList[0];
                            record.GoodsName = sList[1];
                            record.GoodsAmount = int.Parse(sList[2]);
                            record.GoodsDate = sList[3];

                            _scanList.Add(record);
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }


            }
            //foreach (MyGoods record in FrmMain.ScanGoodsList)
            //{

            //}
        }
        #endregion


    }
}